"""
CSV文件读取工具模块
"""

import csv
import os
from typing import List, Optional, Dict, Any
from ..config import ConfigManager


class CSVUtils:
    """CSV文件读取工具类"""
    
    def __init__(self, config_manager: ConfigManager = None):
        """
        初始化CSV工具类
        
        Args:
            config_manager: 配置管理器
        """
        self.config_manager = config_manager or ConfigManager()
        self.data_source_config = self.config_manager.get('robot.data_source', {})
    
    def get_mobiles_from_csv(self, page: int = 0) -> List[str]:
        """
        从CSV文件获取手机号列表
        
        Args:
            page: 页码（从0开始）
            
        Returns:
            手机号列表
        """
        csv_file = self.data_source_config.get('csv_file', 'data/customer.csv')
        page_size = self.data_source_config.get('page_size', 10)
        
        # 确保使用绝对路径
        if not os.path.isabs(csv_file):
            # 获取项目根目录
            current_dir = os.path.dirname(os.path.abspath(__file__))
            # 从 src/utils/ 向上两级到项目根目录
            project_root = os.path.dirname(os.path.dirname(current_dir))
            csv_file = os.path.join(project_root, csv_file)
        
        if not os.path.exists(csv_file):
            print(f"CSV文件不存在: {csv_file}")
            return []
        
        try:
            mobiles = []
            with open(csv_file, 'r', encoding='utf-8') as file:
                reader = csv.DictReader(file)
                rows = list(reader)
                
                # 计算分页
                start = page * page_size
                end = start + page_size
                page_rows = rows[start:end]
                
                # 提取手机号
                for row in page_rows:
                    mobile = row.get('mobile', '').strip()
                    if mobile:
                        mobiles.append(mobile)
                
                return mobiles
                
        except Exception as e:
            print(f"读取CSV文件失败: {e}")
            return []
    
    def get_mobile_count_from_csv(self) -> int:
        """
        获取CSV文件中的手机号总数
        
        Returns:
            手机号总数
        """
        csv_file = self.data_source_config.get('csv_file', 'data/customer.csv')
        
        # 确保使用绝对路径
        if not os.path.isabs(csv_file):
            current_dir = os.path.dirname(os.path.abspath(__file__))
            project_root = os.path.dirname(os.path.dirname(current_dir))
            csv_file = os.path.join(project_root, csv_file)
        
        if not os.path.exists(csv_file):
            print(f"CSV文件不存在: {csv_file}")
            return 0
        
        try:
            with open(csv_file, 'r', encoding='utf-8') as file:
                reader = csv.DictReader(file)
                count = 0
                for row in reader:
                    mobile = row.get('mobile', '').strip()
                    if mobile:
                        count += 1
                return count
                
        except Exception as e:
            print(f"读取CSV文件失败: {e}")
            return 0
    
    def get_all_mobiles_from_csv(self) -> List[str]:
        """
        获取CSV文件中的所有手机号
        
        Returns:
            所有手机号列表
        """
        csv_file = self.data_source_config.get('csv_file', 'data/customer.csv')
        
        # 确保使用绝对路径
        if not os.path.isabs(csv_file):
            current_dir = os.path.dirname(os.path.abspath(__file__))
            project_root = os.path.dirname(os.path.dirname(current_dir))
            csv_file = os.path.join(project_root, csv_file)
        
        if not os.path.exists(csv_file):
            print(f"CSV文件不存在: {csv_file}")
            return []
        
        try:
            mobiles = []
            with open(csv_file, 'r', encoding='utf-8') as file:
                reader = csv.DictReader(file)
                for row in reader:
                    mobile = row.get('mobile', '').strip()
                    if mobile:
                        mobiles.append(mobile)
                return mobiles
                
        except Exception as e:
            print(f"读取CSV文件失败: {e}")
            return []
    
    def add_mobile_to_csv(self, mobile: str, name: str = "") -> bool:
        """
        添加手机号到CSV文件
        
        Args:
            mobile: 手机号
            name: 姓名（可选）
            
        Returns:
            是否成功
        """
        csv_file = self.data_source_config.get('csv_file', 'data/customer.csv')
        
        # 确保使用绝对路径
        if not os.path.isabs(csv_file):
            current_dir = os.path.dirname(os.path.abspath(__file__))
            project_root = os.path.dirname(os.path.dirname(current_dir))
            csv_file = os.path.join(project_root, csv_file)
        
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(csv_file), exist_ok=True)
            
            # 检查文件是否存在
            file_exists = os.path.exists(csv_file)
            
            with open(csv_file, 'a', newline='', encoding='utf-8') as file:
                writer = csv.writer(file)
                
                # 如果文件不存在，写入表头
                if not file_exists:
                    writer.writerow(['id', 'mobile', 'name'])
                
                # 获取下一个ID
                next_id = 1
                if file_exists:
                    with open(csv_file, 'r', encoding='utf-8') as read_file:
                        reader = csv.DictReader(read_file)
                        rows = list(reader)
                        if rows:
                            next_id = max(int(row.get('id', 0)) for row in rows) + 1
                
                # 写入新行
                writer.writerow([next_id, mobile, name])
                return True
                
        except Exception as e:
            print(f"添加手机号到CSV文件失败: {e}")
            return False

    def test_csv_file(self) -> bool:
        """
        测试CSV文件是否存在
        
        Returns:
            是否存在
        """
        csv_file = self.data_source_config.get('csv_file', 'data/customer.csv')
        return os.path.exists(csv_file) 